<?php
namespace app\api\model;

use think\Model;

class Order extends Base
{
    protected $table = 'order';
    protected $autoWriteTimestamp = 'datetime';

    public function OrderProducts()
    {
        return $this->hasMany('OrderProduct','order_id','id');

    }

    public function getOrder($id,$token)
    {
        $user = $this->token($token);
        $data = [];
        $data['products'] = $this->with(['OrderProducts','OrderProducts.product'])->where('id',$id)->find();

        $data['address'] = Address::where('user_id',$user->user_id)->find();

        return $data;
        
    }

    public function confirm($id,$address_id)
    {

        $order = $this->where('id',$id)->update(['address_id'=>$address_id,'status'=>2]);

        if ($order){

            return true;
        }

        return false;
    }
    
    

    public function createOrder($token)
    {
        $user = $this->token($token);

        $data = [];
        $data['total_price'] = [];

        try{

            $carts =  Cart::all(['user_id'=>$user->user_id]);

            foreach ($carts as $cart){

                $cart['price'] = Product::where('id',$cart['product_id'])->find()->price * $cart['num'];
                array_push($data['total_price'],$cart['price']);

            }

            $data['total_price'] = array_sum($data['total_price']);
            $data['order_no'] = date('YmdHis').rand(1000,9999);
            $data['user_id'] = $user->user_id;

            $order = $this->create($data);

            foreach ($carts as $cart){

                OrderProduct::create(['order_id'=>$order->id,'product_id'=>$cart['product_id'],'count'=>$cart['num']]);

            }

            Cart::where('id','>=',1)->where('user_id',$user->user_id)->delete();


            $id = $order->id;

        }catch (\Exception $e){

            $id = false;

        }

        return $id;

    }

    public function lists($token)
    {
        $user = $this->token($token);

        $orders = $this->with(['OrderProducts','OrderProducts.product'])->where('user_id',$user->user_id)->select();

        if ($orders){

            return $orders;
        }

        return false;

    }

    public function take($id)
    {
        $order = $this->where('id',$id)->update(['status'=>5]);

        if ($order){

            return true;
        }

        return false;

    }


    public function cancel($id)
    {
        $order = $this->destroy($id);

        if ($order){

            OrderProduct::destroy(['order_id'=>$id]);

            return true;

        }


        return false;


    }
}